package com.zxc.gulimall.product.service.impl;

import com.zxc.gulimall.product.dao.CategoryBrandRelationDao;
import com.zxc.gulimall.product.service.CategoryBrandRelationService;
import com.zxc.gulimall.product.vo.BrandRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.common.utils.PageUtils;
import com.zxc.common.utils.Query;

import com.zxc.gulimall.product.dao.BrandDao;
import com.zxc.gulimall.product.entity.BrandEntity;
import com.zxc.gulimall.product.service.BrandService;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /*
    * 找出所有brandId相等的数据，并且封装到BrandRespVo的实体类中
    * */
    @Override
    public List<BrandRespVo> selectBrandListByBrandId(List<Long> collect) {
        List<BrandEntity> brandEntities = this.listByIds(collect);
        List<BrandRespVo> collect1 = brandEntities.stream().map(brandEntity -> {
            BrandRespVo brandRespVo = new BrandRespVo();
            brandRespVo.setBrandId(brandEntity.getBrandId());
            brandRespVo.setBrandName(brandEntity.getName());
            return brandRespVo;
        }).collect(Collectors.toList());
        return collect1;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //1、获取key，模糊查询
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<BrandEntity>();
        if (!StringUtils.isEmpty(key)){
            //需要进行模糊检索,可能直接搜索Id，或者名字
            queryWrapper.eq("brand_id",key).or().like("name",key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        //保证品牌和分类关系表的冗余字段数据一致
        this.updateById(brand);

        //如果name不为空说明需要修改更新品牌名，需要更新关系表里面的数据
        if (!StringUtils.isEmpty(brand.getName())){
            //同步更新其他关联表的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
            //TODO 更新其他关联
        }
    }
}